package com.suoyue.store.service.impl;

import com.suoyue.store.entity.User;
import com.suoyue.store.mapper.UserMapper;
import com.suoyue.store.service.IUserservice;
import com.suoyue.store.service.ex.PasswordErrorException;
import com.suoyue.store.service.ex.ServiceException;
import com.suoyue.store.service.ex.UserNotFoundException;
import com.suoyue.store.service.ex.UsernameDuplicatedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements IUserservice {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void regist(User user) {
        String username=user.getUsername();
        User result=userMapper.findByUserName(username);
        if(result!=null){
            throw new UsernameDuplicatedException("用户名被占用");
        }
        Integer rows=userMapper.insert(user);
        if(rows!=1){
            throw new ServiceException("注册失败,存在未知异常");
        }
    }

    @Override
    public User login(String username, String password) {
        // 调用userMapper的findByUsername()方法，根据参数username查询用户数据
        User result = userMapper.findByUserName(username);
        // 判断查询结果是否为null
        if (result == null) {
            // 是：抛出UserNotFoundException异常
            throw new UserNotFoundException("用户数据不存在的错误");
        }
        // 判断查询结果中的密码，与以上得到的密码是否不一致
        if (!result.getPassword().equals(password)) {
            // 是：抛出PasswordNotMatchException异常
            throw new PasswordErrorException("密码验证失败的错误");
        }
        // 创建新的User对象
        User user = new User();
        // 将查询结果中的uid、username、avatar封装到新的user对象中
        user.setUid(result.getUid());
        user.setUsername(result.getUsername());
        user.setEmail(result.getEmail());
        // 返回新的user对象
        return user;
    }

    @Override
    public User findUserByUid(Integer uid) {
        // 调用userMapper的findByUsername()方法，根据参数username查询用户数据
        User result = userMapper.findByUid(uid);
        // 判断查询结果是否为null
        if (result == null) {
            // 是：抛出UserNotFoundException异常
            throw new UserNotFoundException("用户数据不存在的错误");
        }


        // 创建新的User对象
        User user = new User();
        // 将查询结果中的uid、username、avatar封装到新的user对象中
        user.setUid(result.getUid());
        user.setUsername(result.getUsername());
        user.setEmail(result.getEmail());
        // 返回新的user对象
        return user;
    }


}
